import React, { useState } from 'react';
import {
  Box,
  Container,
  Paper,
  Typography,
  List,
  ListItem,
  ListItemAvatar,
  ListItemText,
  Avatar,
  IconButton,
  Tooltip,
  Divider,
  useTheme,
  useMediaQuery,
  Pagination,
  Fab,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Button,
  Snackbar,
  Alert
} from '@mui/material';
import { motion } from 'framer-motion';
import DeleteIcon from '@mui/icons-material/Delete';
import PersonAddIcon from '@mui/icons-material/PersonAdd';
import MessageIcon from '@mui/icons-material/Message';
import { useNavigate } from 'react-router-dom';
import { useFriends } from '../FriendsContext';
import { Friend } from '../services/FriendService';
import { useAuth } from '../../auth/AuthContext';
import MessagePopup from '../../messages/components/MessagePopup';

const FriendList: React.FC = () => {
  const { friends, removeFriend, addFriend, loading, error, checkFriendship } = useFriends();
  const { user } = useAuth();
  const theme = useTheme();
  const navigate = useNavigate();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
  const [page, setPage] = useState(1);
  const itemsPerPage = 5;
  
  // 添加好友相关状态
  const [openAddDialog, setOpenAddDialog] = useState(false);
  const [friendId, setFriendId] = useState('');
  const [friendIdError, setFriendIdError] = useState('');
  const [snackbar, setSnackbar] = useState<{open: boolean, message: string, severity: 'success' | 'error' | 'info'}>({open: false, message: '', severity: 'success'});
  
  // 删除好友确认对话框状态
  const [deleteConfirmDialog, setDeleteConfirmDialog] = useState<{open: boolean, friendId: number, friendName: string}>({open: false, friendId: 0, friendName: ''});

  // 私信对话框状态
  const [messageDialog, setMessageDialog] = useState<{open: boolean, userId: string, userName: string}>({open: false, userId: '', userName: ''});
  
  const currentFriends = friends.slice(
    (page - 1) * itemsPerPage,
    page * itemsPerPage
  );

  // 处理添加好友对话框打开
  const handleOpenAddDialog = () => {
    setOpenAddDialog(true);
    setFriendId('');
    setFriendIdError('');
  };
  
  // 处理添加好友对话框关闭
  const handleCloseAddDialog = () => {
    setOpenAddDialog(false);
  };
  
  // 处理添加好友
  const handleAddFriend = async () => {
    // 验证好友ID
    if (!friendId.trim()) {
      setFriendIdError('请输入好友ID');
      return;
    }
    
    const id = parseInt(friendId.trim());
    if (isNaN(id) || id <= 0) {
      setFriendIdError('请输入有效的好友ID（必须是正整数）');
      return;
    }
    
    // 检查是否是自己
    if (user && id.toString() === user.id) {
      setFriendIdError('不能添加自己为好友');
      return;
    }
    
    try {
      // 检查是否已经是好友
      const isFriend = await checkFriendship(id);
      if (isFriend) {
        setOpenAddDialog(false);
        setSnackbar({open: true, message: '该用户已经是您的好友', severity: 'info'});
        return;
      }
      
      await addFriend(id);
      setOpenAddDialog(false);
      setSnackbar({open: true, message: '好友添加成功', severity: 'success'});
    } catch (error) {
      console.error('添加好友失败:', error);
      setSnackbar({open: true, message: '添加好友失败，请稍后重试', severity: 'error'});
    }
  };
  
  // 处理删除好友确认对话框打开
  const handleOpenDeleteConfirm = (friendId: number, friendName: string, e: React.MouseEvent) => {
    e.stopPropagation();
    setDeleteConfirmDialog({open: true, friendId, friendName});
  };
  
  // 处理删除好友确认对话框关闭
  const handleCloseDeleteConfirm = () => {
    setDeleteConfirmDialog({...deleteConfirmDialog, open: false});
  };
  
  // 处理确认删除好友
  const handleConfirmDelete = async () => {
    try {
      await removeFriend(deleteConfirmDialog.friendId);
      setSnackbar({open: true, message: '好友删除成功', severity: 'success'});
    } catch (error) {
      console.error('删除好友失败:', error);
      setSnackbar({open: true, message: '删除好友失败，请稍后重试', severity: 'error'});
    } finally {
      handleCloseDeleteConfirm();
    }
  };
  
  // 处理私信好友
  const handleMessageFriend = (friendId: number, friendName: string, e: React.MouseEvent) => {
    e.stopPropagation();
    // 打开私信对话框
    setMessageDialog({
      open: true,
      userId: friendId.toString(),
      userName: friendName
    });
  };
  
  // 处理关闭私信对话框
  const handleCloseMessageDialog = () => {
    setMessageDialog({...messageDialog, open: false});
  };
  
  // 处理Snackbar关闭
  const handleCloseSnackbar = () => {
    setSnackbar({...snackbar, open: false});
  };

  return (
    <Container maxWidth="md">
      <Box
        component={motion.div}
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
        sx={{ mt: 4, mb: 4 }}
      >
        <Paper 
          elevation={3} 
          sx={{ 
            p: 3,
            borderRadius: 2,
            background: theme.palette.background.paper,
            boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)'
          }}
        >
          <Typography 
            variant="h5" 
            gutterBottom 
            sx={{
              fontWeight: 600,
              color: theme.palette.primary.main,
              mb: 3
            }}
          >
            我的好友
          </Typography>
          {loading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
              <Typography>加载中...</Typography>
            </Box>
          ) : error ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
              <Typography color="error">{error}</Typography>
            </Box>
          ) : friends.length === 0 ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
              <Typography>暂无好友</Typography>
            </Box>
          ) : (
            <List sx={{ mb: 2 }}>
            {currentFriends.map((friend, index) => (
              <motion.div
                key={friend.id}
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
              >
                <ListItem
                  sx={{
                    mb: 2,
                    borderRadius: 2,
                    transition: 'all 0.3s ease',
                    backgroundColor: theme.palette.background.default,
                    '&:hover': {
                      backgroundColor: theme.palette.action.hover,
                      cursor: 'pointer',
                      transform: 'translateX(8px)'
                    }
                  }}
                  secondaryAction={
                    <Box sx={{ display: 'flex' }}>
                      <Tooltip title="发送私信">
                        <IconButton
                          edge="end"
                          aria-label="message"
                          onClick={(e) => handleMessageFriend(friend.id, friend.username, e)}
                          sx={{ mr: 1 }}
                        >
                          <MessageIcon />
                        </IconButton>
                      </Tooltip>
                      <Tooltip title="删除好友">
                        <IconButton
                          edge="end"
                          aria-label="delete"
                          onClick={(e) => handleOpenDeleteConfirm(friend.id, friend.username, e)}
                        >
                          <DeleteIcon />
                        </IconButton>
                      </Tooltip>
                    </Box>
                  }
                >
                  <ListItemAvatar>
                    <Avatar 
                      src={friend.avatar} 
                      alt={friend.username}
                      sx={{ 
                        width: 50, 
                        height: 50,
                        border: `2px solid ${theme.palette.primary.main}`,
                        boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)'
                      }} 
                    />
                  </ListItemAvatar>
                  <ListItemText
                    primary={
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        {friend.username}
                      </Box>
                    }
                  />
                </ListItem>
                {index < currentFriends.length - 1 && (
                  <Divider
                    key={`divider-${friend.id}`}
                    component={motion.div}
                    initial={{ opacity: 0, scaleX: 0 }}
                    animate={{ opacity: 1, scaleX: 1 }}
                    transition={{ delay: 0.2, duration: 0.3 }}
                    sx={{ my: 1 }}
                  />
                )}
              </motion.div>
            ))}
          </List>
          )}
          <Box
            sx={{
              display: 'flex',
              justifyContent: 'center',
              mt: 3,
              '& .MuiPagination-ul': {
                gap: 1
              }
            }}
          >
            <Pagination
              count={Math.ceil(friends.length / itemsPerPage)}
              page={page}
              onChange={(_, value) => setPage(value)}
              color="primary"
              size={isMobile ? 'small' : 'medium'}
              showFirstButton
              showLastButton
            />
          </Box>
        </Paper>
      </Box>
      
      {/* 添加好友浮动按钮 */}
      <Fab 
        color="primary" 
        aria-label="添加好友" 
        sx={{ 
          position: 'fixed', 
          bottom: 24, 
          right: 24,
          boxShadow: '0 8px 16px rgba(0, 0, 0, 0.2)'
        }}
        onClick={handleOpenAddDialog}
      >
        <PersonAddIcon />
      </Fab>
      
      {/* 添加好友对话框 */}
      <Dialog open={openAddDialog} onClose={handleCloseAddDialog}>
        <DialogTitle>添加好友</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            margin="dense"
            id="friendId"
            label="好友ID"
            type="text"
            fullWidth
            variant="outlined"
            value={friendId}
            onChange={(e) => {
              setFriendId(e.target.value);
              setFriendIdError('');
            }}
            error={!!friendIdError}
            helperText={friendIdError}
            sx={{ mt: 1 }}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseAddDialog}>取消</Button>
          <Button onClick={handleAddFriend} variant="contained" color="primary">
            添加
          </Button>
        </DialogActions>
      </Dialog>
      
      {/* 删除好友确认对话框 */}
      <Dialog open={deleteConfirmDialog.open} onClose={handleCloseDeleteConfirm}>
        <DialogTitle>删除好友</DialogTitle>
        <DialogContent>
          <Typography>确定要删除好友 {deleteConfirmDialog.friendName} 吗？此操作不可撤销。</Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDeleteConfirm}>取消</Button>
          <Button onClick={handleConfirmDelete} variant="contained" color="error">
            删除
          </Button>
        </DialogActions>
      </Dialog>
      
      {/* 私信对话框 */}
      <MessagePopup 
        open={messageDialog.open}
        onClose={handleCloseMessageDialog}
        userId={messageDialog.userId}
        userName={messageDialog.userName}
      />
      
      {/* 提示消息 */}
      <Snackbar 
        open={snackbar.open} 
        autoHideDuration={6000} 
        onClose={handleCloseSnackbar}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert 
          onClose={handleCloseSnackbar} 
          severity={snackbar.severity} 
          sx={{ width: '100%' }}
        >
          {snackbar.message}
        </Alert>
      </Snackbar>
    </Container>
  );
};

export default FriendList;